package org.west.sky.frame.activiti.study.chapter8;

import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.List;

/**
 * author: chz
 * date: 2024/9/6
 * description: 原生sql查询历史流程实例
 */
public class RunDemo8_9 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo8_9 runDemo8_3 = new RunDemo8_9();
        runDemo8_3.runDemo();
    }

    private void runDemo() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter8/Chapter8_1.bpmn20.xml");
        System.out.println("流程定义ID:" + processDefinition.getId() + ",流程定义key:" + processDefinition.getKey());
        //根据流程定义id发起流程
        String prefix = "code_";
        ProcessInstance processInstance1 = runtimeService.startProcessInstanceById(processDefinition.getId(), prefix + 1);
        System.out.println("发起流程实例成功，流程实例id:" + processInstance1.getId());

        ProcessInstance processInstance2 = runtimeService.startProcessInstanceById(processDefinition.getId(), prefix + 2);
        System.out.println("发起流程实例成功，流程实例id:" + processInstance2.getId());


        ProcessInstance processInstance3 = runtimeService.startProcessInstanceById(processDefinition.getId(), prefix + 3);
        System.out.println("发起流程实例成功，流程实例id:" + processInstance3.getId());

        List<HistoricProcessInstance> instances = historyService.createNativeHistoricProcessInstanceQuery().sql("select * from act_hi_procinst where BUSINESS_KEY_ like concat(#{prefix},'%')")
                .parameter("prefix", prefix).list();
        for (HistoricProcessInstance instance : instances) {
            System.out.println("流程实例ID:" + instance.getId() + ",流程定义ID:" + instance.getProcessDefinitionId() + ",流程创建时间:" + sdf.format(instance.getStartTime()));
        }

        processEngine.close();
    }

}
